#!/bin/bash
#Андрей Халиуллин
getname () 
{
	echo $(basename "$1"|sed -e "s/$2$//")
}
checkname ()
{
	if [ -e "$1" ]
	then
		echo "Something with name \"$name\" already exists." >&2
		return 1
	else
		return 0
	fi
}
untar () 
{
	name=$(getname $1 "\.tar")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if tar -xf "../$1" &> /dev/null
		then
			echo "	complete" >&1 
		else
			echo -e "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}

unzip ()
{
	name=$(getname $1 "\.zip")
	if checkname $name
	then
		echo -n "Extracting \"$1\" to \"$name\"..."
		if 7z x $1 -o$name -tzip &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
	fi
}
unrar ()
{
	name=$(getname $1 "\.rar")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if rar x "../$1" &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}
un7z ()
{
	name=$(getname $1 "\.7z")
	if checkname $name
	then
		echo -n "Extracting \"$1\" to \"$name\"..."
		if 7z x $1 -o$name &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
	fi
}
untargz () 
{
	name=$(getname $1 "\.tar\.gz")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if tar -xzf "../$1" &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}
untarbz () 
{
	name=$(getname $1 "\.tar\.bz")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if tar -xjf "../$1" &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}
untarxz () 
{
	name=$(getname $1 "\.tar\.xz")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if tar -xJf "../$1" &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}
untar7z () 
{
	name=$(getname $1 "\.tar\.7z")
	if checkname $name
	then
		mkdir "$name"
		cd "$name"
		echo -n "Extracting \"$1\" to \"$name\"..."
		if 7z x -so ../$1 2>/dev/null|tar -x &> /dev/null
		then 
			echo "	complete" >&1 
		else
			echo "\nShit happens">&2
			exit 1
		fi
		cd "../"
	fi
}
if [ -z $1 ]
then
	echo "No params" >&2
	exit 1
fi

dir=$(pwd)
until [ -z "$1" ]
do
	case "$1" in
		*.tar.7z )	untar7z "$1";;
		*.tar	 )	untar "$1";;
		*.zip	 )	unzip "$1";;
		*.rar	 )	unrar "$1";;
		*.7z	 )	un7z "$1";;
		*.tar.gz )	untargz "$1";;
		*.tar.bz )	untarbz "$1";;
		*.tar.xz )	untarxz "$1";;
		*	 )	echo "Unknow type of \"$1\"";;
	esac
	shift
done
